﻿/* Copyright 2007-2008 dnAnalytics Project.
 *
 * Contributors to this file:
 * Patrick van der Velde
 * Marcus Cuda
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 * 
 * * Redistributions of source code must retain the above copyright notice, this 
 *   list of conditions and the following disclaimer.
 * * Redistributions in binary form must reproduce the above copyright notice, 
 *   this list of conditions and the following disclaimer in the documentation
 *   and/or other materials provided with the distribution.
 * * Neither the name of the dnAnalytics Project nor the names of its contributors
 *   may be used to endorse or promote products derived from this software without
 *   specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
using System;
using dnAnalytics.Properties;

namespace dnAnalytics.LinearAlgebra.Decomposition
{
    internal abstract class AbstractCholesky
    {
        private readonly Matrix mFactor;
        private readonly int mOrder;
        private bool mComputed;
        private bool mIsPositiveDefinite;
        private double mDeterminant = double.MinValue;

        protected AbstractCholesky(Matrix matrix)
        {
            mOrder = matrix.Rows;
            mFactor = matrix.Clone();
        }

        public bool IsPositiveDefinite()
        {
            Compute();
            return mIsPositiveDefinite;
        }

        public Matrix Factor()
        {
            if (!IsPositiveDefinite())
            {
                throw new NotPositiveDefiniteException();
            }

            return mFactor.Clone();
        }

        public double Determinant()
        {
            if (!IsPositiveDefinite())
            {
                throw new NotPositiveDefiniteException();
            }

            if (mDeterminant == double.MinValue)
            {
                lock (mFactor)
                {
                    mDeterminant = 1.0;
                    int rows = mOrder;
                    for (int j = 0; j < rows; j++)
                    {
                        double value = mFactor.ValueAt(j, j);
                        mDeterminant *= (value*value);
                    }
                }
            }
            return mDeterminant;
        }

        public Matrix Solve(Matrix input)
        {
            Matrix result = mFactor.CreateMatrix(mFactor.Columns, input.Columns);
            Solve(input, result);
            return result;
        }

        public void Solve(Matrix input, Matrix result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (mFactor.Rows != input.Rows)
            {
                throw new NotConformableException("input", Resources.ParameterNotConformable);
            }

            if (mFactor.Columns != result.Rows)
            {
                throw new NotConformableException("result", Resources.ParameterNotConformable);
            }

            if (input.Columns != result.Columns)
            {
                throw new NotConformableException("result", Resources.ParameterNotConformable);
            }

            if (!IsPositiveDefinite())
            {
                throw new NotPositiveDefiniteException();
            }

            input.CopyTo(result);
            DoSolve(mFactor, result);
        }

        public Vector Solve(Vector input)
        {
            Vector result = mFactor.CreateVector(mFactor.Columns);
            Solve(input, result);
            return result;
        }

        public void Solve(Vector input, Vector result)
        {
            if (input == null)
            {
                throw new ArgumentNullException("input");
            }
            if (result == null)
            {
                throw new ArgumentNullException("result");
            }

            if (mFactor.Rows != input.Count)
            {
                throw new NotConformableException("input", Resources.ParameterNotConformable);
            }

            if (mFactor.Columns != result.Count)
            {
                throw new NotConformableException("result", Resources.ParameterNotConformable);
            }

            if (!IsPositiveDefinite())
            {
                throw new NotPositiveDefiniteException();
            }

            input.CopyTo(result);
            DoSolve(mFactor, result);
        }

   
        private void Compute()
        {
            if (!mComputed)
            {
                mIsPositiveDefinite = DoCompute(mFactor, mOrder);
                mComputed = true;
            }
        }

        protected abstract bool DoCompute(Matrix data, int order);

        protected abstract void DoSolve(Matrix factor, Matrix result);

        protected abstract void DoSolve(Matrix factor, Vector result);
    }
}
